package com.winit.common.initialize;

import com.winit.common.util.ConfigUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.UserPrincipal;

/**
 * Created by keel2008 on 16/4/14.
 */
@Component
public class BeetleContextValidator {

    /**
     * 在Beetle启动时,判断一下环境因素是否ok.
     *
     * @throws Exception
     */
    @PostConstruct
    public void doValidate() throws Exception {

        //开发模式下,无需校验权限.
        if ("true".equals(ConfigUtil.getValue(ConfigUtil.DEV_MODEL))) {
            return;
        }

        Result rs;

        rs = checkApplogPath();
        Assert.isTrue(rs.isSuccess, "Beetle的启动检查发现异常: /usr/local/applogs/beetle/beetle.log的owner:'"
                + rs.msg + "'不是beetle,启动无法正常运行,请删除该文件后再用beetle启动服务器.");

        rs = checkBeetlePath();
        Assert.isTrue(rs.isSuccess, "Beetle的启动检查发现异常: /usr/local/Beetle文件夹的owner:'"
                + rs.msg + "'不是beetle,系统将无法正常启动,请将该文件夹及以下的owner置为beetle.");

        rs = checkCurrentUser();
        Assert.isTrue(rs.isSuccess, "Beetle的启动检查发现异常: 当前进程用户'"
                + rs.msg + "' 不是beetle,系统将无法正常启动,请使用beetle用户启动应用服务器.");


    }


    /**
     *
     * @return
     */
    private Result checkCurrentUser() {

        String currentUser = System.getProperty("user.name");
        return new Result("beetle".equals(currentUser), currentUser);
    }

    /**
     * 检查/usr/local/Beetle权限.
     *
     * @return
     * @throws Exception
     */
    private Result checkBeetlePath() throws Exception {

        String contextPath = ConfigUtil.getValue(ConfigUtil.ROOT_PATH);

        String username = getFileOwner(contextPath + "/Beetle");

        return new Result("beetle".equals(username), username);
    }

    /**
     *
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    private String getFileOwner(String filePath) throws Exception {

        Path path = Paths.get(filePath);

        if (!path.toFile().exists()){
            return "File Not Exists";
        }

        UserPrincipal owner = Files.getOwner(path);
        return owner.getName();
    }

    private Result checkApplogPath() throws Exception {

        String username = getFileOwner(ConfigUtil.getValue(ConfigUtil.APPLOG_PATH));

        return new Result("beetle".equals(username), username);
    }


    private class Result {

        Boolean isSuccess;
        String msg;

        Result(Boolean isSuccess, String msg) {
            this.isSuccess = isSuccess;
            this.msg = msg;
        }

    }


}
